package car_rental.dao;

import javax.persistence.EntityManager;

public class TransactionalDao {
	
	protected interface Transactional<R> {
		R run(EntityManager entityManager) throws Exception;
	}
	
	private final EntityManager getEntityManager() {
		return DaoUtils.getLocalManager();
	}

	protected <R> R doTransactional(final Transactional<R> transactional) throws Exception {
		final EntityManager entityManager = getEntityManager();
		try {
			entityManager.getTransaction().begin();
			final R result = transactional.run(entityManager);
			entityManager.getTransaction().commit();
			return result;
		} catch (Exception e) {
			try {
				entityManager.getTransaction().rollback();
			} catch (Exception e1) {
			}
			throw e;
		} finally {
			try {
				entityManager.close();
			} catch (Exception e1) {
			}
		}
	}
}
